package com.ews.onlineexchange.service.schedule;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import com.ews.onlineexchange.service.BlackListService;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UserBlacklistTimer {

	@Resource
	TimerService timerService;

	@Inject
	EntityManager entityManager;
	@Inject
	BlackListService blackListService;

	@PostConstruct
	public void init() {
		ScheduleExpression schedule = new ScheduleExpression();
		schedule.dayOfWeek("*");
		schedule.hour("*/50");
		timerService.createCalendarTimer(schedule, new TimerConfig("userBlacklistTimer", false));

		// check();
	}

	private static final String QUERY_ALL_SUPPLIER_EQL = "" 
			+ "	SELECT	serviceSupplier "
			+ "	FROM			ServiceSupplier serviceSupplier ";

	private static final String QUERY_ALL_BUYER_EQL = "" 
			+ "	SELECT	serviceBuyer "
			+ "	FROM			ServiceBuyer serviceBuyer ";

	@Timeout
	public void check() {		
//		Session session = entityManager.unwrap( Session.class );
//		ScrollableResults sr = session.createQuery(QUERY_ALL_SUPPLIER_EQL).setCacheMode( CacheMode.IGNORE )
//		        .scroll( ScrollMode.FORWARD_ONLY );
//		while (sr.next()) {
//			ServiceSupplier supplier = (ServiceSupplier) sr.get(0);Client client = ClientBuilder.newClient();
//			String cnname = supplier.getCnname();
//			String creditCode = supplier.getCreditCode();
//	 		      if(blackListService.validateUserInBlackList(cnname, creditCode)) {
//	 		    	  keycloakUserService.disableUser(supplier);
//	 		      }
//			
//		}
//		
//		query = session.createQuery(QUERY_ALL_BUYER_EQL);
//		ScrollableResults sr1 = query.scroll(ScrollMode.FORWARD_ONLY);
//		while (sr1.next()) {
//			ServiceBuyer buyer = (ServiceBuyer) sr1.get(0);
//			String cnname = buyer.getCnname();
//			String creditCode = buyer.getCreditCode();
// 		      if(blackListService.validateUserInBlackList(cnname, creditCode)) {
// 		    	  keycloakUserService.disableUser(buyer);
// 		      }
// 		    }
	}
}
